class RoomsController < AdminController

  before_filter :login_required, :only => [:new, :create]

  def new
    @page_title = "Creation d'une salle"
    respond_to do |format|
      format.html
      format.js
    end
  end

  def create
    @room = Room.new(params[:room])
    @room.save!
    flash[:notice] = "Création de la salle #{@room.name}"
    respond_to do |format|
      format.html { redirect_to '/'}
      format.js 
    end
  rescue ActiveRecord::RecordInvalid
    if params[:room][:name].empty?    
      flash[:notice] = "Un nom de salle est requis !"
    else
      flash[:notice] = "Le nom est déja pris !"
    end
    respond_to do |format|
      format.html { render :action => 'new' }
      format.js { render :action => 'error_create.rjs' }
    end
  end

  def edit
    @room = Room.find params[:id]
    @page_title = "Edition de la salle #{@room.name}"
    rescue ActiveRecord::RecordNotFound
      respond_to do |format|
        format.html { render :action => 'new' }
      end
  end

  def update
    @room = Room.find params[:id]
    if @room.update_attributes params[:room]
      redirect_to :controller => :rooms, :action => 'show'
    else
      render :action => :edit
    end
  end
  
  def show
    begin
      @room_view = Room.find params[:id]
      @page_title = "Salle #{@room_view.name}"
    rescue ActiveRecord::RecordNotFound
      @room_view = nil
      @page_title = "Salle inconnu"
    end
    @rooms = Room.find :all
    @incidents = Incident.find :all, :conditions => [ 'resolved_at IS NULL' ]
    respond_to do |format|
      format.html 
      format.js 
    end
  end

  def destroy
    unless logged_in?
      redirect_to :action => 'show', :id => params[:id] 
    else
      @room = Room.find params[:id]
      @room.destroy
      flash[:notice] = 'Suppression de la salle'
      redirect_to '/'
    end
  rescue ActiveRecord::RecordNotFound
    flash[:notice] = 'Pas de salle possible à supprimer'
    redirect_to '/'
  end

  def make_draggable_init
    @computer = Room.find(params[:id]).computers
    respond_to do |format|
      format.js
    end
  end

  def ajoute_elt_box
    @computer = Computer.find params[:id].gsub!(/computer_/, '')
    @room_delete = Room.find @computer.room.id
    @room = Room.find params[:target]
    @computer.room = @room 
    @computer.save
    
    
    respond_to do |format|
      format.js
    end
  end

end
